//
//  SRHomePageViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/3/25.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRHomePageViewController.h"
#import "FZHomeViewModel.h"
#import "FZHomeConstants.h"
#import "FZHomeService.h"
#import "FZHomeCourseModel.h"
#import "FZHomeSectionModel.h"

#import <MTLJSONAdapter.h>
#import <MJRefresh.h>
#import "FZHomeBannerCollectionViewCell.h"
#import "SRMessageCenterViewController.h"


#import "FZMCCacheManager.h"
#import "SRCommonConstants.h"
#import "FZAdvertisementService.h"
#import "FZAdvertisementModel.h"
#import "FZUpdateVerisonModel.h"

#import "UIAlertView+SRBlocks.h"


@interface SRHomePageViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate, FZHomeViewModelDelegate>


@property (strong, nonatomic) UICollectionView *collectionView;

@property (strong, nonatomic) FZHomeService *service;

@property (strong, nonatomic) FZHomeViewModel *viewModel;
@property (copy, nonatomic) NSArray *sections;
//@property (copy, nonatomic) NSArray *bannerModels;
@property (strong, nonatomic) FZHomeSectionModel *bookSectionModel;
@property (strong, nonatomic) FZHomeSectionModel *bannerSectionModel;

@property (strong, nonatomic) FZStyleSheet *css;
@property (assign, nonatomic) BOOL hasShowLoginView;

@property (strong, nonatomic) NSIndexPath *scrollIndexPath;

@end

@implementation SRHomePageViewController


#pragma mark - Init & life Circle

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)viewDidLoad {
    [super viewDidLoad];
        // Do any additional setup after loading the view.
//    self.title = @"我的教材";

    self.css = [FZStyleSheet currentStyleSheet];
    
    [self setupNavigationBarButtonItem];
    [self setupView];
    [self setupData];
    
//    [self showLoadingViewWithCompletedBlock:^(BOOL finished) {
//        [self mainQueryAction:NO];
//    }];
    
    [self getUserInfoFromConfig];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bookDidChangeNotification:) name:SRUserBookDidChangeNotification object:nil];
    
    [self queryData:NO];
    
    [self checkUpdateVersion];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
}

- (void)setupView {
    
//    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, 0, 60, 44)];
    titleLabel.text = @"英语趣点读";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont systemFontOfSize:17.f];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    CGFloat edgeSpace = kFZHomeCollectionViewEdgeSpace;
        //    CGFloat itemWidth = (SCREEN_WIDTH - 3 * edgeSpace) / 2;
        //    CGFloat ratio = 160.f / 107.f;
        //    CGFloat itemHeight = itemWidth / ratio;
    
        //    layout.itemSize = CGSizeMake(itemWidth, itemHeight);
    layout.minimumLineSpacing = edgeSpace;
    layout.minimumInteritemSpacing = edgeSpace;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.sectionInset = UIEdgeInsetsMake(edgeSpace, edgeSpace, 0, edgeSpace);
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    collectionView.backgroundColor = self.css.color_2;
    collectionView.alwaysBounceVertical = YES;
    
    [self registerCollectionViewCell:collectionView];
    
    collectionView.dataSource = self;
    collectionView.delegate = self;
    
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    WEAKSELF
    [self.collectionView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf mainQueryAction:YES];
    }];
//
//    self.loadingView.clickButtonBlock = ^(id sender) {
//        [weakSelf showLoadingQueryData];
//    };
//    
//    self.loadingView.tapViewBlock = ^(id sender) {
//        [weakSelf showLoadingQueryData];
//    };
}



- (void)getUserInfoFromConfig {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"homepage" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    NSArray *sectionJSONArray = jsonDictionary[@"data"];
    NSArray *modelArray = [MTLJSONAdapter modelsOfClass:[FZHomeSectionModel class] fromJSONArray:sectionJSONArray error:nil];
    [self parseHomeModuleData:modelArray];
}

- (void)showLoadingQueryData {
//    [self showLoadingViewWithCompletedBlock:^(BOOL finished) {
        [self queryData:NO];
//    }];
}

- (void)setupData {
    FZMCCacheManager *cacheManager = [FZMCCacheManager defaultManager];
    [cacheManager readBookInfoFromFile];
    
    self.service = [[FZHomeService alloc] init];
    self.viewModel = [[FZHomeViewModel alloc] initWithCollectionView:self.collectionView info:nil delegate:self];
    [self.viewModel reloadCurrentBook];
    
}

- (void)setupNavigationBarButtonItem {
    UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setImage:[UIImage imageNamed:@"icon_message_btn"] forState:UIControlStateNormal];
    [rightButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    rightButton.frame = CGRectMake(0, 0, 44, 44);
    [rightButton addTarget: self action: @selector(onMessageButton:) forControlEvents: UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    [self setRightBarButtonItem:rightBarItem];
}


- (void)registerCollectionViewCell:(UICollectionView *)collectionView {
    [collectionView registerNib:[UINib nibWithNibName:kFZHomeBaseCollectionViewCell bundle:nil] forCellWithReuseIdentifier:kFZHomeBaseCollectionViewCell];
    [collectionView registerNib:[UINib nibWithNibName:kFZHomeBannerCollectionViewCell bundle:nil] forCellWithReuseIdentifier:kFZHomeBannerCollectionViewCell];
    [collectionView registerNib:[UINib nibWithNibName:kFZHomeAlbumCollectionViewCell bundle:nil] forCellWithReuseIdentifier:kFZHomeAlbumCollectionViewCell];
    [collectionView registerNib:[UINib nibWithNibName:kSRHomeFeatureCollectionViewCell bundle:nil] forCellWithReuseIdentifier:kSRHomeFeatureCollectionViewCell];

        //register Header class
    [collectionView registerNib:[UINib nibWithNibName:kFZHomeCollectionViewSectionHeaderView bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kFZHomeCollectionViewSectionHeaderView];
    [collectionView registerNib:[UINib nibWithNibName:kFZHomeCollectionViewSectionFooterView bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:kFZHomeCollectionViewSectionFooterView];
    
    [collectionView registerNib:[UINib nibWithNibName:kFZHomeHotVideoSectionFooterView bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:kFZHomeHotVideoSectionFooterView];
}

#pragma mark - Event

- (void)onMessageButton:(id)sender {
    SRMessageCenterViewController *vc = [[SRMessageCenterViewController alloc] init];
    [self pushViewController:vc animated:YES];
}

#pragma mark - notification SEL


- (void)outLoginRefreshData:(NSNotification *)notification {
    [self mainQueryAction:YES];
}

- (void)loginRefreshData:(NSNotification *)notification {
    [self mainQueryAction:YES];
    
    [self loginSuccessAction:notification];
}

- (void)loginWithOtherEquipment:(NSNotification *)notification {
    [self mainQueryAction:YES];
}

- (void)bookDidAddNotification:(NSNotification *)notification {
    [self.collectionView reloadData];
}

- (void)bookDidChangeNotification:(NSNotification *)notification {
    
    [self.viewModel reloadCurrentBook];
    
    [self.collectionView reloadData];
}

#pragma mark - Query & Event

- (void)mainQueryAction:(BOOL)isRefresh {
    
    [self queryData:isRefresh];
}

- (void)queryData:(BOOL)isRefresh {
    [self queryBannerData];
//    [self.collectionView reloadData];
    
//    [self.service queryDataWithSuccessBlock:^(NSInteger statusCode, NSString *message, id responseDataObject){
//        [weakSelf.collectionView.header endRefreshing];
//        
//        if (statusCode == kFZRequestStatusCodeSuccess) {
//            NSArray *sections = responseDataObject;
//            
//            
//            if (sections && [sections isKindOfClass:[NSArray class]]) {
//                [weakSelf hideLoadingView];
////                weakSelf.sections = sections;
//                [weakSelf parseHomeModuleData:sections];
//
//                
//            } else {
//                if (!isRefresh) {
//                    if ([weakSelf.viewModel numberOfSections] > 0){
//                            //有数据显示
//                        [weakSelf hideLoadingView];
//                    } else {
//                        [weakSelf emptyLoadingViewWithTitle:nil];
//                    }
//                }
//            }
//        } else {
//            [weakSelf failedLoadingViewWithTitle:message];
//        }
//        
//    } failBlock:^(id responseObject, NSError *error) {
//        if (!isRefresh) {
//            if ([weakSelf.viewModel numberOfSections] > 0){
//                    //有数据显示
//                [weakSelf hideLoadingView];
//            } else {
//                [weakSelf failedLoadingViewWithTitle:nil];
//            }
//        } else {
//            if ([weakSelf.viewModel numberOfSections] > 0){
//                [weakSelf hideLoadingView];
//            } else {
//                [weakSelf failedLoadingViewWithTitle:nil];
//            }
//            
//            [weakSelf.collectionView.header endRefreshing];
//        }
//        
//    }];
    
}


//- (void)queryHotVideoData {
//    WEAKSELF
//    NSInteger randNum = 0;
//    if (self.hotSectionModel) {
//        randNum = self.hotSectionModel.randNum;
//    }
//    
//    [self.service queryHotVideoDataWithRand:randNum SuccessBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
//        if (statusCode == kFZRequestStatusCodeSuccess && responseDataObject) {
//                //替换下一批
//            [weakSelf parseHotVideoData:responseDataObject];
//        }
//        
//    } failBlock:^(id responseObject, NSError *error) {
//        
//    }];
//}


- (void)parseHomeModuleData:(NSArray *)sections {
        //添加过滤ishow专区处理，若不是ishow学员，就不显示
    NSMutableArray *sectionModels = [@[] mutableCopy];
    
    for (int i = 0; i < [sections count]; ++ i) {
        
        FZHomeSectionModel *item = sections[i];
        
        if (![self isSupportedModule:item.module]) {
                //不支持的模块不显示；
            continue;
        }
        else if ([item.module isEqualToString:kHomeModuleSlider]) {
            self.bannerSectionModel = item;
            if (item.sliders.count <= 0) {
                    //                [sectionModels removeObject:item];
                continue;
            }
        } else if ([item.module isEqualToString:kHomeModuleAlbum]){
            self.bookSectionModel = item;
        }
        
        [sectionModels addObject:item];
    }
    
    
//    if (self.bookSectionModel) {
//        if ([cacheManager.books count] > 0) {
//            self.bookSectionModel.albums = cacheManager.books;
//        } else {
//            [cacheManager.books addObjectsFromArray:self.bookSectionModel.albums];
//        }
//    }
    
    [self.viewModel setSectionModels:sectionModels];
}

- (BOOL)isSupportedModule:(NSString *)module {
    if ([module isEqualToString:kHomeModuleSlider]) {
        return YES;
    } else if ([module isEqualToString:kHomeModuleCourse]) {
        return YES;
    } else if ([module isEqualToString:kHomeModuleAlbum]) {
        return YES;
    }
    else if ([module isEqualToString:kHomeModuleFeatures]) {
        return YES;
    }
    else {
            //不支持的模块类型，不添加显示
        return NO;
    }
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    viewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:viewController animated:animated];
}


- (void)showLoginViewController {
//    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//    [delegate setupLoginViewController];
}


/**
 *  用户登录状态发生变化，需要刷新数据
 *
 */
- (void)userDidChangeLoginNotification:(NSNotification *)notification {
        //    NSLog(@"userDidChangeLoginNotification");
    [self showLoadingQueryData];
}

//- (void)parseHotVideoData:(FZHomeSectionModel *)model {
//    [self.viewModel.sectionModels enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        FZHomeSectionModel *item = obj;
//        if ([item.module isEqualToString:kHomeModuleCourse] && [item.identifier isEqualToString:kHomeHotVideoSectionID]) {
//                //今日热门
//            self.hotSectionModel = model;
//            [self.viewModel.sectionModels replaceObjectAtIndex:idx withObject:model];
//            *stop = YES;
//        }
//    }];
//    
//    [self.collectionView reloadData];
//}

- (void)refrehData {
    [self queryData:NO];
}

- (void)queryBannerData {
    WEAKSELF
    [FZAdvertisementService getAdsWithType:FZAdsTypeBanner success:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf.collectionView.header endRefreshing];
        
        if (statusCode == kFZRequestStatusCodeSuccess && responseDataObject) {
            NSArray *adLists = responseDataObject;
            if ([adLists isKindOfClass:[NSArray class]] && [adLists count] > 0) {
                ;
                weakSelf.bannerSectionModel.sliders = adLists;
            }
        }
        
        [weakSelf.collectionView reloadData];

    } failure:^(id responseObject, NSError *error) {
        [weakSelf.collectionView.header endRefreshing];
        [weakSelf.collectionView reloadData];
    }];
}

-(void)checkUpdateVersion {
    
    NSString *urlString = [[SRAPICreater sharedInstance] APIWithName:@"basic_getVersion"];
    NSDictionary *params = @{@"app":@"IOS"};
    [[SRNetWorkManager sharedInstance] GET:urlString needCache:NO parameters:params responseClass:[FZUpdateVerisonModel class] success:^(NSInteger statusCode, NSString *message, id dataObject) {
        if (statusCode == kFZRequestStatusCodeSuccess && dataObject) {
            FZUpdateVerisonModel* updateVersionModel = dataObject;
            
            long  long serverTimeStamp = [updateVersionModel.timeStamp longLongValue];
            long  long clientTimeStamp = ([[NSDate date] timeIntervalSince1970]);
            long long  timeStamp = serverTimeStamp - clientTimeStamp;
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setValue:[NSNumber numberWithLongLong:timeStamp] forKey:KSeverClientTimeStamp];
            [defaults setValue:updateVersionModel.notReviewStatus forKey:kSRAppNotReviewStatusKey];
    
            
            [defaults synchronize];
            
//            [[NSNotificationCenter defaultCenter] postNotificationName:kAppFeaturesNeedShowDidChangeNotification object:nil];
            
            float versionFloat = [updateVersionModel.versionCode floatValue];
            float nowversion   = [APPVersionCode floatValue];
            WEAKSELF
            if (versionFloat > nowversion) {
                if (updateVersionModel.isKeyupdate && updateVersionModel.isKeyupdate.intValue > 0) {
                    [[[UIAlertView alloc] initWithTitle:@"本次版本为重要更新，旧版本可能会引起无法使用和崩溃错误，请您更新"
                                                message:updateVersionModel.info
                                       cancelButtonItem:nil
                                       otherButtonItems:[RIButtonItem itemWithLabel:@"更新" action:^{
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:APPSTOREURL]];
                        
                        UIAlertView*alertview ;
                        for (UIView *view in self.view.subviews)
                        {
                            if ([view isKindOfClass:[UIAlertView class]])
                            {
                                alertview = (UIAlertView *)view;
                            }
                        }
                        if (![alertview.title isEqualToString:@"本次版本为重要更新，旧版本可能会引起无法使用和崩溃错误，请您更新"])
                        {
                            [weakSelf checkUpdateVersion];
                        }
                        
                        
                        
                    }], nil] show];
                }
                else
                {
                    [[[UIAlertView alloc] initWithTitle:@"检测到新版本"
                                                message:updateVersionModel.info
                                       cancelButtonItem:[RIButtonItem itemWithLabel:@"不再提示" action:^{
                        
                        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                        [userDefaults  setValue:updateVersionModel.version forKey:@"passVersion"];
                        [userDefaults synchronize];
                        
                    }]
                                       otherButtonItems:[RIButtonItem itemWithLabel:@"更新" action:^{
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:APPSTOREURL]];
                    }], nil] show];
                }
            }

        }
        
    } failure:^(id responseObject, NSError *error) {
        
    }];
}


#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView  {
    return [self.viewModel numberOfSections];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.viewModel numberOfItemsInSection:section];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    return [self.viewModel cellForItemAtIndexPath:indexPath];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    return [self.viewModel viewForSupplementaryElementOfKind:kind atIndexPath:indexPath];
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    if ([cell isKindOfClass:[FZHomeBannerCollectionViewCell class]]) {
            //banner 广告
            //        NSLog(@"12313");
    } else {
        [self.viewModel didSelectItemForIndexPath:indexPath];
    }
}


#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return [self.viewModel sizeForItemAtIndexPath:indexPath];
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return [self.viewModel insetForSectionAtIndex:section];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return [self.viewModel referenceSizeForHeaderInSection:section];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return [self.viewModel referenceSizeForFooterInSection:section];
}


#pragma mark - FZHomeViewModelDelegate
- (void)homeViewModelShowLoginViewController:(FZHomeViewModel *)homeViewModel {
    [self showLoginViewController];
}
- (void)homeViewModel:(FZHomeViewModel *)homeViewModel pushViewController:(UIViewController *)viewController {
    [self pushViewController:viewController animated:YES];
}

//- (void)homeViewModel:(FZHomeViewModel *)homeViewModel onChangeHotVideoButton:(UIButton *)button object:(id)object {
//    [self queryHotVideoData];
//}

- (void)homeViewModel:(FZHomeViewModel *)homeViewModel isEditing:(BOOL)isEditing {
    if (isEditing) {
        
    } else {
        
    }
    
    [self.collectionView reloadData];
}

- (void)homeViewModel:(FZHomeViewModel *)homeViewModel showMessage:(NSString *)message {
    [self showHUDHintWithText:message];
}

#pragma mark - login success notification

- (void)loginSuccessAction:(NSNotification *)notification {
    
}


@end
